<?php

namespace App\Models;

use Hyn\Tenancy\Traits\UsesTenantConnection;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\AssetCategory
 *
 * @property int $id
 * @property string $name
 * @property int|null $parent_id
 * @property string|null $deleted_at
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AssetCategory[] $children
 * @property-read int|null $children_count
 * @property-read mixed $is_primary
 * @property-read \App\Models\AssetCategory $parent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory primary()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory secondary()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory whereParentId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AssetCategory whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class AssetCategory extends Model
{
    use UsesTenantConnection;
    protected $guarded = [];

    protected $appends = ['is_primary'];

    protected $hidden = ['created_at', 'deleted_at', 'updated_at'];

    public function getIsPrimaryAttribute()
    {
        return empty($this->attributes['parent_id']);
    }

    public function children()
    {
        return $this->hasMany(AssetCategory::class, 'parent_id', 'id');
    }

    public function parent()
    {
        return $this->hasOne(AssetCategory::class, 'id', 'parent_id');
    }

    public function scopePrimary($query)
    {
        return $query->whereNull('parent_id');
    }
    public function scopeSecondary($query)
    {
        return $query->whereNotNull('parent_id');
    }
}
